package cn.majingjing.core.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @description
 * 
 * @author Administrator - JingjingMa
 * @Email <a href="majinding888@163.com">majinding888@163.com</a>
 * @date 2015-9-5 下午3:01:40
 * @version 6.0
 * @DevTool Created By Eclipse 4.3
 * 
 */

public class JaxbXmlTools {

	public static String objToxml(Object obj) throws JAXBException {
		StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

		jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");// 编码格式
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
		// 是否省略xml头信息（<?xml version="1.0" encoding="utf-8" standalone="yes"?>）
		jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		jaxbMarshaller.marshal(obj, baos);
		xml.append(new String(baos.toByteArray()));
		return xml.toString();
	}

	public static String objToxmlForWeixin(Object obj,String encoding) throws JAXBException {
		StringBuilder xml = new StringBuilder();
		JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

		jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);// 编码格式
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
		// 是否省略xml头信息（<?xml version="1.0" encoding="utf-8" standalone="yes"?>）
		jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		jaxbMarshaller.marshal(obj, baos);
		xml.append(new String(baos.toByteArray()));
		return xml.toString();
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T xmlToObj(String xml,Class<T> clazz) throws JAXBException, UnsupportedEncodingException {
		ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("utf-8"));
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		return (T)jaxbUnmarshaller.unmarshal(bais);
	}
	
}
